using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;

using FlickrNet;
using System.Collections.Generic;

namespace FlickrManager
{
    public partial class Default : System.Web.UI.Page
    {
        /// <summary>
        /// Sets Per Page.
        /// </summary>
        private const int SetsPerPage = 5;

        /// <summary>
        /// Photos Per Page.
        /// </summary>
        private const int PhotosPerPage = 18;

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            //check fro style
            if (Session["style"] != null)
            {
                stylesheet.Href = Session["style"].ToString();
            }

            SetSets();

            SetPhotos();

            SetCurrentPhoto();
            
        }

        /// <summary>
        /// Sets the sets.
        /// </summary>
        private void SetSets()
        {
            //always load groups with paging          
            try
            {
                side_menu.Controls.Clear();

                IList<FlickrUserWebConfig> list = GetUsers();

                IList<Photoset> sets = new List<Photoset>();

                foreach (FlickrUserWebConfig user in list)
                {
                    Flickr flickr = new Flickr(user.ApiKey, user.Secret);

                    Photosets photoSet = flickr.PhotosetsGetList(user.UserId);

                    foreach (Photoset var in photoSet.PhotosetCollection)
                    {
                        var.OwnerId = user.UserId;
                        sets.Add(var);
                    }
                }
                    Control uc;
                    Type ucType;
                    PropertyInfo ucType_TextValue;

                    //paging
                    int page;
                    int.TryParse(Request.QueryString["groupPage"], out page);
                    if (page == 0)
                        page = 1;

                    int from = (page - 1) * SetsPerPage;
                    int tto = Math.Min((page - 1) * SetsPerPage + SetsPerPage, sets.Count);

                    for (int i = from; i < tto; i++)
                    {
                        uc = LoadControl("Group.ascx");

                        ucType = uc.GetType();
                        ucType_TextValue = ucType.GetProperty("SetGroup");
                        ucType_TextValue.SetValue(uc, sets[i], BindingFlags.SetProperty, null, null, null);

                        side_menu.Controls.Add(uc);
                    }
                

                //add pages
                int pages = sets.Count / SetsPerPage;
                if ((sets.Count % SetsPerPage) != 0)
                {
                    pages++;
                }

                if (pages > 1)
                {
                    setPagesPanel.Controls.Clear();

                    for (int i = 1; i <= pages; i++)
                    {
                        HyperLink hh = new HyperLink();
                        hh.NavigateUrl = "Default.aspx?group=" + Request.QueryString["group"] + "&name=" +
                        Request.QueryString["name"] + "&imageUrl=" + Request.QueryString["imageUrl"] + "&groupPage=" + i + "&setPage=" + Request.QueryString["setPage"] + "&userId=" + Request.QueryString["userId"];
                        hh.ID = "hhset" + i;
                        hh.CssClass = "myLink";
                        hh.Text = i.ToString();

                        if (i == page)
                        {
                            hh.Enabled = false;
                            hh.ForeColor = System.Drawing.Color.Gray;
                        }

                        setPagesPanel.Controls.Add(hh);
                    }
                }

            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// Sets the groups.
        /// </summary>
        private void SetPhotos()
        {
            //check for sets
            if (!string.IsNullOrEmpty(Request.QueryString["group"]))
            {
                thumbs.Controls.Clear();

                title.InnerText = Request.QueryString["name"];

                FlickrUserWebConfig user = GetCurrentUser();

                //search for photos in group
                Flickr flickr = new Flickr(user.ApiKey, user.Secret);

                Photoset photos = flickr.PhotosetsGetPhotos(Request.QueryString["group"], 1, 500);

                Control uc;
                Type ucType;
                PropertyInfo ucType_TextValue;

                //paging
                int page;
                int.TryParse(Request.QueryString["setPage"], out page);
                if (page == 0)
                    page = 1;

                int from = (page - 1) * PhotosPerPage;
                int tto = Math.Min((page - 1) * PhotosPerPage + PhotosPerPage, photos.PhotoCollection.Length);

                for (int i = from; i < tto; i++)
                {
                    uc = LoadControl("Thumb.ascx");

                    ucType = uc.GetType();
                    ucType_TextValue = ucType.GetProperty("SetPhoto");
                    ucType_TextValue.SetValue(uc, photos.PhotoCollection[i], BindingFlags.SetProperty, null, null, null);

                    thumbs.Controls.Add(uc);
                }

                //add pages
                int pages = photos.PhotoCollection.Length / PhotosPerPage;
                if ((photos.PhotoCollection.Length % PhotosPerPage) != 0)
                {
                    pages++;
                }

                if (pages > 1)
                {
                    Panel p = new Panel();

                    for (int i = 1; i <= pages; i++)
                    {
                        HyperLink hh = new HyperLink();
                        hh.NavigateUrl = "Default.aspx?group=" + Request.QueryString["group"] + "&name=" +
                        Request.QueryString["name"] + "&imageUrl=" + Request.QueryString["imageUrl"] + "&setPage=" + i + "&groupPage=" + Request.QueryString["groupPage"] + "&userId=" + Request.QueryString["userId"];
                        hh.ID = "hhphoto" + i;
                        hh.CssClass = "myLink";
                        hh.Text = i.ToString();

                        if (i == page)
                        {
                            hh.Enabled = false;
                            hh.ForeColor = System.Drawing.Color.Gray;
                        }

                        p.Controls.Add(hh);
                    }

                    photosPagesPanel.Controls.Add(p);
                }
            }
        }

        /// <summary>
        /// Sets the current photo.
        /// </summary>
        private void SetCurrentPhoto()
        {
            //look for photo
            if (!string.IsNullOrEmpty(Request.QueryString["imageUrl"]))
            {
                try
                {
                    FlickrUserWebConfig user = GetCurrentUser();

                    //search for photos in group
                    Flickr flickr = new Flickr(user.ApiKey, user.Secret);

                    imagePanel.Controls.Clear();
                    Image image = new Image();
                    image.ImageUrl = flickr.PhotosGetInfo(Request.QueryString["imageUrl"]).MediumUrl;
                    image.Width = 445;
                    image.Height = 355;

                    imagePanel.Controls.Add(image);
                }
                catch (Exception)
                {
                }
            }
        }

        /// <summary>
        /// Gets the current user.
        /// </summary>
        /// <returns></returns>
        private FlickrUserWebConfig GetCurrentUser()
        {
            string userId = Request.QueryString["userId"];

            int userCount = int.Parse(ConfigurationManager.AppSettings["FlickrUserCount"]);

            for (int i = 1; i <= userCount; i++)
            {
                string usId = ConfigurationManager.AppSettings["FlickrUserId" + i];

                if(userId.Equals(usId))
                {
                    FlickrUserWebConfig user = new FlickrUserWebConfig();
                    user.UserId = userId;
                    user.ApiKey = ConfigurationManager.AppSettings["FlickrApiKey" + i];
                    user.Secret = ConfigurationManager.AppSettings["FlickrSecret" + i];

                    return user;
                }
            }

            return null;
        }

        /// <summary>
        /// Gets the users.
        /// </summary>
        /// <returns></returns>
        private IList<FlickrUserWebConfig> GetUsers()
        {
            IList<FlickrUserWebConfig> users = new List<FlickrUserWebConfig>();

            int userCount = int.Parse(ConfigurationManager.AppSettings["FlickrUserCount"]);

            for (int i = 1; i <= userCount; i++)
            {
                string usId = ConfigurationManager.AppSettings["FlickrUserId" + i];

                FlickrUserWebConfig user = new FlickrUserWebConfig();
                user.UserId = usId;
                user.ApiKey = ConfigurationManager.AppSettings["FlickrApiKey" + i];
                user.Secret = ConfigurationManager.AppSettings["FlickrSecret" + i];

                users.Add(user);

            }

            return users;
        }

        /// <summary>
        /// Handles the Click event of the btnGreen control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
        protected void btnGreen_Click(object sender, ImageClickEventArgs e)
        {
            stylesheet.Href = "style/colour.css";
            Session["style"] = "style/colour.css";
        }

        /// <summary>
        /// Handles the Click event of the btnBlue control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
        protected void btnBlue_Click(object sender, ImageClickEventArgs e)
        {
            stylesheet.Href = "style/colour_blue.css";
            Session["style"] = "style/colour_blue.css";
        }

        /// <summary>
        /// Handles the Click event of the btnRed control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
        protected void btnRed_Click(object sender, ImageClickEventArgs e)
        {
            stylesheet.Href = "style/colour_red.css";
            Session["style"] = "style/colour_red.css";
        }

        /// <summary>
        /// Handles the Click event of the btnPurple control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
        protected void btnPurple_Click(object sender, ImageClickEventArgs e)
        {
            stylesheet.Href = "style/colour_purple.css";
            Session["style"] = "style/colour_purple.css";
        }

        /// <summary>
        /// Handles the Click event of the btnOrange control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
        protected void btnOrange_Click(object sender, ImageClickEventArgs e)
        {
            stylesheet.Href = "style/colour_orange.css";
            Session["style"] = "style/colour_orange.css";
        }


    }
}
